package com.zzl.study.demo.controller;

import com.alibaba.cloud.ai.memory.redis.RedissonRedisChatMemoryRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static org.springframework.ai.chat.memory.ChatMemory.CONVERSATION_ID;

/**
 * 带有对话记忆功能的聊天Controller
 *
 * @author: zhangzl
 * @date: 2025/9/29 15:38
 * @version: 1.0
 */
@RestController
@RequestMapping("/memory-chat")
public class MemoryChatController {

    /**
     * 聊天客户端
     */
    private final ChatClient chatClient;

    /**
     * 最大记忆消息数
     */
    private final static int MAX_MESSAGES = 100;

    /**
     * 聊天对话存储仓库
     */
    private final MessageWindowChatMemory messageWindowChatMemory;

    public MemoryChatController(ChatClient.Builder builder, RedissonRedisChatMemoryRepository redisChatMemoryRepository) {
        this.messageWindowChatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(redisChatMemoryRepository)
                .maxMessages(MAX_MESSAGES)
                .build();
        this.chatClient = builder
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(messageWindowChatMemory).build())
                .build();
    }

    /**
     * 聊天调用
     *
     * @param query          查询
     * @param conversationId 会话ID
     * @return 响应结果
     */
    @GetMapping("/call")
    public String call(@RequestParam("query") String query, @RequestParam("conversation_id") String conversationId) {
        return this.chatClient.prompt(query)
                .advisors(
                        a -> a.param(CONVERSATION_ID, conversationId)
                )
                .call().content();
    }

    /**
     * 获取对话消息
     *
     * @param conversationId 会话ID
     * @return 对话消息
     */
    @GetMapping("/messages")
    public List<Message> messages(@RequestParam("conversation_id") String conversationId) {
        return this.messageWindowChatMemory.get(conversationId);
    }

}
